<template>
	<view class="">
		<u--form labelPosition="left" :model="model1" :rules="rules" ref="uForm" labelWidth="180rpx">
			<view class="bg-w pd15">
				<u-form-item label="供应商" prop="supplier_dictText" ref="item1" :required="true" @click="showVendor=true">
					<u--input v-model="model1.supplier_dictText" border="surround" suffixIcon="arrow-down"
						placeholder="请选择供应商" suffixIconStyle="color: #909399" disabledColor="#fff" disabled></u--input>
				</u-form-item>
				<u-form-item label="所属商户" prop="commercialOwner_dictText" ref="item1" :required="true"
					@click="showCommercial=true">
					<u--input v-model="model1.commercialOwner_dictText" border="surround" suffixIcon="arrow-down"
						placeholder="请选择商户" suffixIconStyle="color: #909399" disabledColor="#fff" disabled></u--input>
				</u-form-item>
				<u-form-item label="单据日期" prop="documentDate" ref="item1" :required="true" @click="showDate=true">
					<u--input v-model="model1.documentDate" border="surround" placeholder="请选择单据日期" disabledColor="#fff"
						disabled></u--input>
				</u-form-item>
				<!-- <u-form-item label="单据编号" prop="documentNumber" :required="true" ref="item1">
					<u--input v-model="model1.documentNumber" border="surround" clearable disabled
						placeholder="请输入单据编号"></u--input>
				</u-form-item> -->
			</view>
			<view class="plr15 bg-w mt10" style="padding-bottom: 30rpx;">
				<view class="flex spaceb plt15">
					<view>商品</view>
					<!-- <view class="flex">
					<view class="flex alcenter">
						<view class="mr5">
							<u-icon name="scan" size="20" color="#6A6A6A"></u-icon>
						</view>
						<view>扫码</view>
					</view>
					<view class="flex alcenter ml20" @click="$u.route('/pages/basicData/commodity/list')">
						<view class="mr5">
							<u-icon name="list-dot" size="20" color="#6A6A6A"></u-icon>
						</view>
						<view>选择</view>
					</view>
				</view> -->
				</view>
				<view class="plt15 border-top" v-for="(item,index) in model1.purchaseReceiptFormList" :key="index"
					@click="showboxClick(index,item.productNumber)">
					<view class="flex spaceb">
						<view class="flex alcenter">
							<view class="number">{{index+1}}</view>
							<view class="ml10">{{item.products}}</view>
						</view>
						<view class="flex alcenter">
							<!-- <view class="mr10">x{{item.number}}</view> -->
							<u-icon name="arrow-right" size="16" color="#6A6A6A"></u-icon>
						</view>
					</view>
					<view class="cl-hui mt5">所入仓库：{{item.warehouseText||''}}</view>
					<view class="cl-hui mt5">本次入库数量：{{item.currentReceiptQty||''}}</view>
					<view class="cl-hui mt5">剩余数量：{{item.remain}}</view>
					<view class="cl-hui mt5">采购单价：{{item.unitPrice||''}}</view>
					<!-- <view class="cl-hui">合计：{{item.purchaseUnitPrice*item.number}}</view> -->
					<view class="flex spaceb mt5">
						<view class="cl-hui">备注：{{item.remarks||''}}</view>
						<!-- <view class="" @click="delOrder(index)">
						<u-icon name="trash" size="20" color="#6A6A6A"></u-icon>
					</view> -->
					</view>
				</view>
				<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" text="无数据"
					v-if="model1.purchaseReceiptFormList==''" marginTop="50rpx">
				</u-empty>
			</view>
			<view v-if="model1.purchaseReceiptFormList!=''">
				<view class="pd15 mt10 bg-w">
					<span>总条数:{{model1.purchaseReceiptFormList.length}}</span>
					<span class="ml10">总数量:{{totalNum}}</span>
					<span class="ml10">总金额:{{totalPrice}}</span>
				</view>
				<view class="bg-w pd15 mt10">
					<u-form-item label="单据金额" prop="documentAmount" ref="item1">
						<u--input v-model="model1.documentAmount" border="surround" placeholder="" disabled></u--input>
					</u-form-item>
					<u-form-item label="单据编号" prop="documentNumber" ref="item1">
						<u--input v-model="model1.documentNumber" border="surround" placeholder="" disabled></u--input>
					</u-form-item>
					<u-form-item label="实付金额" prop="actualPayment" ref="item1" :required="true">
						<u--input v-model="model1.actualPayment" border="surround" placeholder="请输入实付金额"></u--input>
					</u-form-item>
				</view>
				<view class="bg-w pd15 mt10">
					<u-form-item label="制单人" prop="creator_dictText" ref="item1" @click="showCreator=true"
						:required="true">
						<u--input v-model="model1.creator_dictText" border="surround" placeholder="请选择制单人"
							suffixIcon="arrow-down" suffixIconStyle="color: #909399"></u--input>
					</u-form-item>
					<u-form-item label="结算账户" prop="settlementAccount_dictText" ref="item1" @click="showAccount=true"
						:required="true">
						<u--input v-model="model1.settlementAccount_dictText" border="surround" placeholder="请选择结算账户"
							suffixIcon="arrow-down" suffixIconStyle="color: #909399"></u--input>
					</u-form-item>
					<u-form-item label="单据附件" prop="docAnnex" ref="item1">
						<u--input v-model="model1.docAnnex" border="surround" placeholder="请上传单据附件" suffixIcon="attach"
							suffixIconStyle="color: #909399"></u--input>
					</u-form-item>
					<u-form-item label="备注" prop="remarks" ref="item1">
						<u--textarea v-model="model1.remarks" border="surround" placeholder="请输入备注"></u--textarea>
					</u-form-item>
				</view>
			</view>
		</u--form>
		<view style="height: 200rpx;"></view>
		<view class="footer">
			<u-button type="primary" text="保存" @click="procureOrderClick"></u-button>
		</view>
		<u-picker :show="showCommercial" :columns="commercial" @confirm="confirmCommercial" @cancel="close"></u-picker>
		<u-picker :show="showCreator" :columns="creator" @confirm="confirmCreator" @cancel="close"></u-picker>
		<!-- <u-picker :show="showReview" :columns="reviewStatus" @confirm="confirmReview" @cancel="close"></u-picker> -->
		<u-picker :show="showVendor" :columns="vendor" @confirm="confirmVendor" @cancel="close"></u-picker>
		<u-picker :show="showAccount" :columns="account" @confirm="confirmAccount" @cancel="close"></u-picker>
		<u-picker :show="showWarehouse" :columns="baseWarehouseList" @confirm="confirmWarehouse" @cancel="close"
			keyName="warName"></u-picker>
		<!-- <u-calendar :show="showDate" :mode="mode" :maxDate="maxDate" :defaultDate="defaultDateMultiple"
			@confirm="confirmDate" @close="close"></u-calendar> -->
		<u-datetime-picker :show="showDate" v-model="timeStamp" mode="date" @confirm="confirmDate"
			@cancel="close"></u-datetime-picker>
		<u-popup :show="showbox" @close="close" @open="open" mode="bottom" :closeable="true" zIndex="10074">
			<view class="pd15">
				<view class="text-center">单据明细</view>
				<u--form labelPosition="left" :model="detailed" :rules="detailRules" ref="uFormDetail"
					labelWidth="180rpx">
					<u-form-item label="所入仓库" prop="warehouseText" ref="item1" @click="showWarehouse=true"
						:required="true">
						<u--input v-model="detailed.warehouseText" border="surround" placeholder="请选择所入仓库"
							suffixIcon="arrow-down" suffixIconStyle="color: #909399"></u--input>
					</u-form-item>
					<u-form-item label="本次入库数量" prop="currentReceiptQty" ref="item1" :required="true">
						<u--input v-model="detailed.currentReceiptQty" border="surround"
							placeholder="请输入本次入库数量"></u--input>
					</u-form-item>
					<u-form-item label="采购单价" prop="unitPrice" ref="item1" :required="true">
						<u--input v-model="detailed.unitPrice" border="surround" placeholder="请输入采购单价"></u--input>
					</u-form-item>
					<u-form-item label="备注" prop="remarks" ref="item1">
						<u--textarea v-model="detailed.remarks" border="surround" placeholder="请输入备注"></u--textarea>
					</u-form-item>
				</u--form>
				<u-button type="primary" text="保存" @click="confirmProcureOrder"></u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const d = new Date()
	const year = d.getFullYear()
	let month = d.getMonth() + 1
	month = month < 10 ? `0${month}` : month
	const date = d.getDate()
	export default {
		data() {
			return {
				model1: {
					// commercialOwner: "",
					// commercialOwnerText: "",
					// creator: "",
					// creatorText: "",
					// docAnnex: "",
					// documentDate: "",
					// documentNumber: "",
					// id: "",
					// procureOrderFormList: [],
					// productNumber: "",
					// remarks: '',

					actualPayment: "",
					commercialOwner: "",
					commercialOwner_dictText: "",
					creator: "",
					creator_dictText: "",
					docAnnex: "",
					documentAmount: 0,
					documentDate: "",
					documentNumber: "",
					procureOrderId: "",
					remarks: "",
					settlementAccount: "",
					settlementAccount_dictText: "",
					supplier: "",
					supplier_dictText: "",
					purchaseReceiptFormList: []
				},
				actions: [{
						name: '男',
					},
					{
						name: '女',
					},
					{
						name: '保密',
					},
				],
				rules: {
					'supplier_dictText': {
						type: 'string',
						required: true,
						message: '请选择供应商',
						trigger: ['change']
					},
					'actualPayment': {
						type: 'string',
						required: true,
						message: '请输入实付金额',
						trigger: ['blur', 'change']
					},
					'settlementAccount_dictText': {
						type: 'string',
						required: true,
						message: '请选择结算账户',
						trigger: ['change']
					}
				},
				showCommercial: false,
				commercial: [
					[]
				],
				showCreator: false,
				creator: [
					[]
				],
				showReview: false,
				reviewStatus: [
					[]
				],
				vendor: [
					[]
				],
				showVendor: false,
				account: [
					[]
				],
				showAccount: false,
				showDate: false,
				mode: 'single',
				minDate: '1970-01-01',
				maxDate: '2100-01-01',
				defaultDateMultiple: `${year}-${month}-${date}`,

				// actualPayment: "100",
				// commercialOwner: "SH-240716-001",
				// creator: "1714471285016895490",
				// docAnnex: null,
				// documentAmount: "100",
				// documentDate: "2024-07-27 00:00:00",
				// documentNumber: "CGRK-240727-014",
				// procureOrderId: "1816696936275689473",
				// purchaseReceiptFormList: [{
				// 	amount: 100
				// 	createBy: "ERP-01"
				// 	createTime: "2024-07-26 12:47:57"
				// 	currentReceiptQty: 5
				// 	currentStock: 121
				// 	entryStatus: "2"
				// 	number: 10
				// 	procureOrderFormId: "1816696936284078082"
				// 	procureOrderId: "1816696936275689473"
				// 	productNumber: "SP-240722-002"
				// 	products: "内衣"
				// 	properties: null
				// 	remain: 8
				// 	remarks: ""
				// 	sysOrgCode: "A01A05"
				// 	unitPrice: 20
				// 	updateBy: "ERP-01"
				// 	updateTime: "2024-07-27 12:43:08"
				// 	warehouse: "001"
				// }, {
				// 	amount: null
				// 	createBy: "ERP-01"
				// 	createTime: "2024-07-26 12:47:57"
				// 	currentReceiptQty: 0
				// 	currentStock: 0
				// 	entryStatus: "1"
				// 	number: 20
				// 	procureOrderFormId: "1816696936317632514"
				// 	procureOrderId: "1816696936275689473"
				// 	productNumber: "SP-240716-003"
				// 	products: "衣柜1"
				// 	properties: null
				// 	remain: 0
				// 	remarks: ""
				// 	sysOrgCode: "A01A05"
				// 	unitPrice: 10
				// 	updateBy: "ERP-01"
				// 	updateTime: "2024-07-27 12:43:08"
				// 	warehouse: "001"
				// }],
				// remarks: "qweqwe",
				// settlementAccount: "ZH-240711-001",
				// supplier: "003",


				timeStamp: Number(new Date()),
				//单据明细
				showbox: false,
				detailed: {
					warehouse: '',
					warehouseText: '',
					currentReceiptQty: '',
					unitPrice: '',
					remarks: ''
				},

				detailRules: {
					'warehouseText': {
						type: 'string',
						required: true,
						message: '请选择仓库',
						trigger: ['change']
					},
					'currentReceiptQty': {
						type: 'string',
						required: true,
						message: '请填写本次入库数量',
						trigger: ['blur', 'change']
					},
					'unitPrice': {
						type: 'string',
						required: true,
						message: '请填写采购单价',
						trigger: ['blur', 'change']
					},
				},
				selectIndex: 0,
				procureOrderFormList: [],
				pageNo: 1,
				pageSize: 9999,
				baseWarehouseList: [
					[]
				],
				showWarehouse: false,
				productNumber: ''
			}
		},
		computed: {
			// 计算本次入库总数量
			totalNum() {
				let totalNum = 0;
				if (this.model1.purchaseReceiptFormList != '') {
					this.model1.purchaseReceiptFormList.map(item => {
						totalNum += Number(item.currentReceiptQty)
					})
					return totalNum
				}
			},
			// 计算本次入库总金额
			totalPrice() {
				let totalPrice = 0;
				if (this.model1.purchaseReceiptFormList != '') {
					this.model1.purchaseReceiptFormList.map(item => {
						totalPrice += Number(item.currentReceiptQty) * Number(item.unitPrice)
					})
					this.model1.documentAmount = totalPrice
					return totalPrice
				}
			},
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			this.getDictItemsCommercialOwner()
			this.getDictItemsSysUser()
			this.stk_cgrk_bill_no()
			this.getDictItemsAccount()
			this.getDictItemsVendor()
			this.getBaseWarehouseList()
			// console.log(options)
			if (!this.$u.test.isEmpty(options.item)) {
				const item = JSON.parse(decodeURIComponent(options.item));
				this.model1 = {
					id: item.id,
					actualPayment: "",
					commercialOwner: item.commercialOwner,
					commercialOwner_dictText: item.commercialOwner_dictText,
					creator: item.creator,
					creator_dictText: item.creator_dictText,
					docAnnex: item.docAnnex,
					documentAmount: 0,
					documentDate: item.documentDate,
					documentNumber: item.documentNumber,
					procureOrderId: "",
					remarks: item.remarks,
					settlementAccount: "",
					settlementAccount_dictText: "",
					supplier: "",
					supplier_dictText: "",
					purchaseReceiptFormList: []
				}
				console.log(this.model1)
				this.queryProcureOrderFormByMainId(item.id)
			}
		},
		onShow() {
			if (!this.$u.test.isEmpty(uni.getStorageSync('procureOrderFormList'))) {
				this.model1.procureOrderFormList = uni.getStorageSync('procureOrderFormList');
			}
			// this.isLogin = checkLogin()
			// if (!this.isLogin) {
			// 	this.isloginBind()
			// 	return false
			// }

		},
		onUnload() {
			uni.removeStorageSync('procureOrderFormList')
		},
		methods: {
			queryProcureOrderFormByMainId(id) {
				this.$apis.queryProcureOrderFormByMainId(id).then(res => {
					const newProps = {
						warehouse: '',
						warehouseText: '',
						currentReceiptQty: 0,
						currentStock: 0,
						procureOrderFormId: ""
					};
					let updatedItems = res.result.map(item => ({
						...item,
						...newProps
					}));
					this.model1.purchaseReceiptFormList = updatedItems
					console.log(this.model1.purchaseReceiptFormList, 'this.model1.purchaseReceiptFormList')
				})
			},
			getBaseWarehouseList() {
				this.$apis.getBaseWarehouseList({
					column: 'createTime',
					order: 'desc',
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					_t: 1721211555986,
				}).then(res => {
					this.baseWarehouseList[0] = res.result.records
				})
			},
			//fin_zh_bill_no账户编号
			stk_cgrk_bill_no() {
				this.$apis.stk_cgrk_bill_no().then(res => {
					this.model1.documentNumber = res.result
				})
			},
			getDictItemsCommercialOwner() {
				this.$apis.getDictItemsCommercialOwner().then(res => {
					this.commercial[0] = res.result
					// this.model1.accCode = res.result
				})
			},
			getDictItemsVendor() {
				this.$apis.getDictItemsVendor().then(res => {
					this.vendor[0] = res.result
					// this.model1.accCode = res.result
				})
			},
			getDictItemsSysUser() {
				this.$apis.getDictItemsSysUser().then(res => {
					this.creator[0] = res.result
				})
			},
			getDictItemsAccount() {
				this.$apis.getDictItemsAccount().then(res => {
					this.account[0] = res.result
				})
			},
			select(e) {
				this.intindex = e
			},
			checkboxChange(n) {
				console.log('change', n);
			},
			open() {
				// console.log('open');
			},
			close() {
				this.showCommercial = this.showDate = this.showbox = this.showCreator = this.showAccount = this
					.showWarehouse = this
					.showVendor = false;
				// console.log('close');
			},
			confirmCommercial(e) {
				const {
					value,
					label
				} = e.value[0];
				this.model1.commercialOwner = value;
				this.model1.commercialOwnerText = label;
				this.close();
			},
			confirmCreator(e) {
				const {
					value,
					label
				} = e.value[0];
				this.model1.creator = value;
				this.model1.creator_dictText = label;
				this.close();
			},
			confirmVendor(e) {
				const {
					value,
					label
				} = e.value[0];
				this.model1.supplier = value;
				this.model1.supplier_dictText = label;
				this.close();
			},
			confirmAccount(e) {
				const {
					value,
					label
				} = e.value[0];
				this.model1.settlementAccount = value;
				this.model1.settlementAccount_dictText = label;
				this.close();
			},
			confirmDate(e) {
				this.model1.documentDate = this.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.close()
			},
			showboxClick(index, productNumber) {
				this.selectIndex = index
				this.showbox = true
				this.productNumber = productNumber
			},
			confirmProcureOrder() {
				this.$refs.uFormDetail.validate().then(res => {
					const selectedForm = this.model1.purchaseReceiptFormList[this.selectIndex];
					if (this.detailed.currentReceiptQty > selectedForm.remain) return this.$u.toast(
						'入库数量不得超出剩余数量，' + '剩余数量为' +
						selectedForm.remain)
					selectedForm.warehouse = this.detailed.warehouse;
					selectedForm.warehouseText = this.detailed.warehouseText;
					selectedForm.currentReceiptQty = Number(this.detailed.currentReceiptQty);
					selectedForm.unitPrice = Number(this.detailed.unitPrice);
					selectedForm.remarks = this.detailed.remarks;
					selectedForm.amount = Number(this.detailed.unitPrice) * Number(this.detailed.currentReceiptQty)
					this.detailed = {
						warehouse: '',
						warehouseText: '',
						currentReceiptQty: '',
						unitPrice: '',
						remarks: ''
					}
					this.close()
					console.log(this.model1.purchaseReceiptFormList)
				}).catch(errors => {})
			},
			confirmWarehouse(e) {
				console.log(e.value[0])
				this.$apis.inventoryInquiryQueryData({
					productNumber: this.productNumber,
					warehouse: e.value[0].warCode,
					_t: 1721211555986
				}).then(res => {
					if (res.code == 200) {
						this.model1.purchaseReceiptFormList[this.selectIndex].currentStock = res.result.inventory
					}
				})
				this.detailed.warehouse = e.value[0].warCode
				this.detailed.warehouseText = e.value[0].warName
				this.showWarehouse = false
			},
			delOrder(index) {
				let that = this
				uni.showModal({
					content: "确认删除吗",
					success(res) {
						if (res.confirm) {
							that.model1.procureOrderFormList.splice(index, 1)
						}
					}
				})
			},
			procureOrderClick() {
				let purchaseReceiptFormList = this.model1.purchaseReceiptFormList.map(item => ({
					amount: item.amount,
					createBy: item.createBy,
					createTime: item.createTime,
					currentReceiptQty: item.currentReceiptQty,
					currentStock: item.currentStock,
					entryStatus: item.entryStatus,
					number: item.number,
					procureOrderFormId: item.id,
					procureOrderId: item.procureOrderId,
					productNumber: item.productNumber,
					products: item.products,
					properties: item.properties,
					remain: item.remain,
					remarks: item.remarks,
					sysOrgCode: item.sysOrgCode,
					unitPrice: item.unitPrice,
					updateBy: item.updateBy,
					updateTime: item.updateTime,
					warehouse: item.warehouse
				}));
				let form = {
					actualPayment: this.model1.actualPayment,
					commercialOwner: this.model1.commercialOwner,
					creator: this.model1.creator,
					docAnnex: this.model1.docAnnex,
					documentAmount: this.model1.documentAmount,
					documentDate: this.model1.documentDate,
					documentNumber: this.model1.documentNumber,
					procureOrderId: this.model1.id,
					remarks: this.model1.remarks,
					settlementAccount: this.model1.settlementAccount,
					supplier: this.model1.supplier,
					purchaseReceiptFormList: purchaseReceiptFormList
				}
				// console.log(form)
				this.$refs.uForm.validate().then(res => {
					this.$apis.purchaseReceiptAdd(form).then(res => {
						if (res.code == 200) {
							this.$u.toast(res.result)
							setTimeout(() => {
								uni.navigateBack()
							}, 1000);
						}
					})
				}).catch(errors => {})
			},
		},
	}
</script>
<style>
	page {
		background-color: #F5F5F5;
	}
</style>
<style lang="scss" scoped>
	.icon {
		border: 1px solid #E0E0E0;
		padding: 8rpx 20rpx;
		border-radius: 10rpx;
	}

	.add {
		background-color: #3247D3;
		padding: 8rpx 20rpx;
		border-radius: 10rpx;
		color: #fff;
	}

	.cl-status {
		color: #6A6A6A;
	}

	.pore {
		position: relative;
	}

	.popBox {
		width: 400rpx;
		height: 100%;
		position: relative;

		.btns {
			position: absolute;
			bottom: 30rpx;
			right: 30rpx;
			left: 30rpx;
			display: flex;
			justify-content: space-around;

			.chongzhi {
				border: 1px solid #E0E0E0;
				padding: 8rpx 30rpx;
				border-radius: 10rpx;
			}

			.confirm {
				padding: 8rpx 30rpx;
				border-radius: 10rpx;
				background-color: #3247D3;
				color: #fff;
			}
		}
	}

	.border-top {
		border-top: 1px solid #F8F8F8;
	}

	.number {
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		background-color: #3247D3;
		color: #fff;
		font-size: 22rpx;
		// padding: 4rpx 10rpx;
		border-radius: 8rpx;
	}

	.footer {
		position: fixed;
		bottom: 0;
		background-color: #fff;
		width: 100%;
		padding: 30rpx;
		z-index: 999;
	}
</style>